using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Ubject = UnityEngine.Object;

public class UIFindAttribute : Attribute
{
    public Type type;

    public UIFindAttribute(Type type)
    {
        this.type = type;
    }
}




[System.Serializable]
public class UIElement
{
    public string member;
    public Ubject main;
}


public class UIModule : MonoBehaviour
{
#if UNITY_EDITOR
    public string classGroup;
#endif
    public List<UIElement> elements = new List<UIElement>();

    private Dictionary<string, UIElement> _keyValues;
    private Dictionary<string, UIElement>  keyValues
    {
        get 
        {
            if (_keyValues == null)
            {
                _keyValues = new Dictionary<string, UIElement>();

                foreach (var element in elements)
                {
                    keyValues.Add(element.member,element);
                }
            }
            return _keyValues;
        }
    }

    public T TryGet<T>(string key) where T : Component
    {
        if (keyValues.TryGetValue(key, out var view))
        {
            return view.main as T;
        }
        return default(T);
    }

    public GameObject TryGet(string key) 
    {
        if (keyValues.TryGetValue(key, out var view))
        {
            if (view.main is GameObject)
                return view.main as GameObject;
            else
                return ((Component)view.main).gameObject;
        }
        return null;
    }

    public Transform TryGetTransform(string key)
    {
        if (keyValues.TryGetValue(key, out var view))
        {
            if (view.main is Transform)
                return view.main as Transform;
            else
                return ((Component)view.main).transform;
        }
        return null;
    }
}
